package risk.control.project.service;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;
import risk.control.project.config.constant.FilePath;
import risk.control.project.entity.repository.TransactionRecordBean;
import risk.control.project.entity.response.RecordRespData;
import risk.control.project.framework.PostService;
import risk.control.project.mapper.record.RecordMapper;
import risk.control.project.poi.record.RecordData;
import risk.control.project.utils.UUIDUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

@Service
public class TakeRecordService extends PostService {

    private static final Logger logger = LoggerFactory.getLogger(TakeRecordService.class);

    @Qualifier("MainSqlSessionFactory")
    private final SqlSessionFactory sqlSessionFactory;

    @Qualifier("JedisPool")
    private final JedisPool jedisPool;


    public TakeRecordService(JedisPool jedisPool, SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
        this.jedisPool = jedisPool;
    }

    /**
     * LIMIT 每页条数
     * OFFSET (页码-1)*每页条数
     *
     * @param pageSize  pageSize
     * @param pageIndex pageIndex(从1开始)
     * @return record
     */
    public String record(String pageSize, String pageIndex) {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            int pSize = Integer.parseInt(pageSize);//每页展示多少条
            int pIndex = Integer.parseInt(pageIndex);//第几页
            if (pIndex < 1) {
                return generateFail("页码不能小于1");
            }
            if (pSize > 100) {
                return generateFail("每页数据量过大");
            }
            int offset = (pIndex - 1) * pSize;
            RecordMapper mapper = session.getMapper(RecordMapper.class);
            Map<String, Integer> params = new HashMap<>();
            params.put("limit", pSize);
            params.put("offset", offset);
            List<TransactionRecordBean> recordList = mapper.queryRecord(params);
            String total = mapper.queryTotal();//查询总计
            //封装数据
            RecordRespData respData = new RecordRespData();
            respData.recordLis = recordList;
            respData.total = total;
            return generateSucceed(respData);
        } catch (Exception e) {
            return generateFail("查询异常");
        }
    }

    public String queryRecordFromWithdrawalTime(String startTime, String endTime, String pageSize, String pageIndex) {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            int pSize = Integer.parseInt(pageSize);//每页展示多少条
            int pIndex = Integer.parseInt(pageIndex);//第几页
            if (pIndex < 1) {
                return generateFail("页码不能小于1");
            }
            if (pSize > 100) {
                return generateFail("每页数据量过大");
            }
            int offset = (pIndex - 1) * pSize;
            RecordMapper mapper = session.getMapper(RecordMapper.class);
            Map<String, Object> params = new HashMap<>();
            params.put("limit", pSize);
            params.put("offset", offset);
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            List<TransactionRecordBean> recordList = mapper.queryRecordFromWithdrawalTime(params);
            String total = mapper.queryTotalFromWithdrawalTime();//查询总计
            //封装数据
            RecordRespData respData = new RecordRespData();
            respData.recordLis = recordList;
            respData.total = total;
            return generateSucceed(respData);
        } catch (Exception e) {
            return generateFail("查询异常");
        }
    }

    public HashMap<String, String> fullQueryRecord(String startTime, String endTime) {
        HashMap<String, String> resMap = new HashMap<>();
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            RecordMapper mapper = session.getMapper(RecordMapper.class);
            Map<String, String> params = new HashMap<>();
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            List<TransactionRecordBean> recordList = mapper.fullQueryRecord(params);
            //开始写数据
            String recordListJsonData = JSON.toJSONString(recordList);//list->json字符串
            //字符串转excel表格
            List<RecordData> dataList = JSON.parseObject(recordListJsonData, new TypeReference<>() {
            });
            // 文件路径
            String fileName = FilePath.CASH_RECORD_FOLDER + "/" + UUIDUtils.generate() + ".xlsx";
            EasyExcel.write(fileName, RecordData.class)//
                    .registerWriteHandler(new SimpleColumnWidthStyleStrategy(30)) // 设置列宽
                    .sheet("Sheet1")//
                    .doWrite(dataList);
            resMap.put("state", "000");
            resMap.put("msg", "文件导出成功");
            resMap.put("filePath", fileName);
        } catch (Exception e) {
            resMap.put("state", "001");
            resMap.put("msg", "文件导出失败：" + e.getMessage());
        }
        return resMap;
    }

    @Async
    public CompletableFuture<String> test() {
        try {
            Thread.sleep(5000);
            return CompletableFuture.completedFuture("你好，正在处理");
        } catch (InterruptedException e) {
            return CompletableFuture.completedFuture("你好，处理失败");
        }
    }
}
